#include "AdventureCardFactory.h"
#include <fstream>
#include "AdventureCard.h"
#include "Instruction.h"
#include "InstructionFactory.h"

#include <string>
using namespace std;

// Loads a single adventure card from the specified file and returns a new object created from the data 
AdventureCard* AdventureCardFactory::makeAdventureCard(std::string iFileName)
{
	string prefName = "Name:";
	string prefDesc = "Desc:";
	string prefImage = "Image:";
	string prefEncounter = "Encounter:";
	string prefInstruction = "Instruction:";
	string imageFile="";
	string instr;
	string name="";
	string desc="";
	int enc=0;

	string line;
	ifstream myfile (iFileName);
	if (myfile.is_open())
	{
		while ( myfile.good() )
		{
			getline (myfile,line);
			if(pref(line, prefName))
				name = line.substr(prefName.size());
			else if (pref(line, prefDesc))
				desc = line.substr(prefDesc.size());
			else if (pref(line, prefEncounter))
				enc = atoi(line.substr(prefEncounter.size()).c_str());
			else if (pref(line, prefImage))
				imageFile = line.substr(prefImage.size()).c_str();
			else if (pref(line, prefInstruction))
				instr = line.substr(prefInstruction.size()).c_str();
			else
				throw "Couldn't load the adventure card - the file has an incorrect fromat.";
		}
		myfile.close();
	}
	else 
	{
		throw "Couldn't load the adventure card - the file doesn't exist or can't be read.";
	}

	QImage *img = new QImage();
	img->load(imageFile.c_str());

	AdventureCard * card = new AdventureCard(name, desc, img);

	Instruction * wInstruction = InstructionFactory::instructionFromString(instr);
	card->setInstruction(wInstruction);

	return card;

}

// Loads an entire deck from a file and returns a pointer to the new vector of cards
vector<AdventureCard *> * AdventureCardFactory::loadFromDeck(std::string iDeckFileName)
{
	vector<AdventureCard *> * vec = new vector<AdventureCard *>();
	string prefFileName = "Card:";
	string fileName = "";
	string line;
	ifstream myfile (iDeckFileName);
	if (myfile.is_open())
	{
		while ( myfile.good() )
		{
			getline (myfile,line);
			if(pref(line, prefFileName))
			{
				fileName = line.substr(prefFileName.size());
				vec->push_back(makeAdventureCard(fileName));
			}
			else
				throw "Couldn't load the adventure card - the file has an incorrect fromat.";
		}
		myfile.close();
	}
	else 
	{
		throw "Couldn't load the adventure card - the file doesn't exist or can't be read.";
	}

	return vec;
}

// Tells whether or not "str" starts with "pref"
bool AdventureCardFactory::pref(string str, string pref)
{
	return (str.compare(0, pref.size(), pref) == 0);
}